package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.CryptoUtil;
import com.zhongkai.StringStatic;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.WebRegLogService;
import com.zhongkai.jedis.JedisClient;
import com.zhongkai.model.utils.TTHelp;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.Chinaset;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * web用户注册 登录
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WebRegLogServiceImpl implements WebRegLogService {


    @Autowired
    private IBaseDao iBaseDao;


    @Autowired
    private JedisClient jedisClient;

    @Override
    public ZhongkaiResult user_registered(String user_name, String pass_word, String set_name, String set_sex, String set_phone, int set_role) {
        if (StringUtils.isNullOrEmpty(user_name) || StringUtils.isNullOrEmpty(pass_word)
                || StringUtils.isNullOrEmpty(set_name) || StringUtils.isNullOrEmpty(set_sex)
                || StringUtils.isNullOrEmpty(set_phone) || set_role == 0
                ) {
            return ZhongkaiResult.build(400, "数据不完整,注册失败");
        }

        Chinaset chinaset = (Chinaset) iBaseDao.get("from Chinaset tb where tb.userName='" + user_name + "' or tb.setPhone='" + set_phone + "'");

        if (chinaset != null) {
            return ZhongkaiResult.build(401, "该手机号或用户名已存在");
        }
        chinaset = new Chinaset();

        chinaset.setUuid(TTHelp.generate()); //设置id

        chinaset.setUserName(user_name);

        //加密
        try {
            String pass = CryptoUtil.encode64(CryptoUtil.SALT, pass_word);

            chinaset.setPassWord(pass); //设置加密后的密码

        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(400, "数据加密失败");
        }

        chinaset.setSetName(set_name);

        chinaset.setSetSex(set_sex);
        chinaset.setSetPhone(set_phone);
        chinaset.setSetRole(set_role);

        String generate = TTHelp.generate(); //生成Token
        chinaset.setToken(StringStatic.REDIS_TOKEN + generate); //存入对象

        ObjectMapper mapper = new ObjectMapper();
        String chinasetJson = null;
        try {
            chinasetJson = mapper.writeValueAsString(chinaset);//转成json
        } catch (IOException e) {
            e.printStackTrace();
            return ZhongkaiResult.build(401, "转换失败,请联系管理员");
        }

        iBaseDao.save(chinaset);

/*        jedisClient.set(StringStatic.REDIS_TOKEN + generate, chinasetJson);  //加入缓存
        jedisClient.expire(StringStatic.REDIS_TOKEN + generate, 604800);//过期时间为一个星期*/

        return ZhongkaiResult.ok(chinaset);

    }


    /**
     * web登录
     */
    @Override
    public ZhongkaiResult user_login(String username, String password) {


        if (StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(password)) {
            return ZhongkaiResult.build(400, "数据不完整,登录失败");
        }

        Chinaset chinaset;
        chinaset = (Chinaset) iBaseDao.get("from Chinaset tb where tb.userName='" + username + "'");

        if (chinaset == null) {
            return ZhongkaiResult.build(401, "用户不存在,登录失败");
        } else {

            String password12 = chinaset.getPassWord();
            String decontent = CryptoUtil.decode64(CryptoUtil.SALT, password12);
            //    System.out.println("解密后：" +  decontent );


            if (password.equals(decontent)) {  //密码正确  设置缓存
                try {
                    //System.out.println(chinaset.getToken());
                    //   Long delete = jedisClient.delete(chinaset.getToken());//生成新token之前删除及以前的

/*                    if (!StringUtils.isNullOrEmpty(chinaset.getToken())){
                        //   Long delete = jedisClient.delete(appUser.getToken());//生成新token之前删除及以前的
                        jedisClient.expire(chinaset.getToken(), 1);//过期时间为0

                    }*/
                    //System.out.println("user_login"+delete);


                    String generate = TTHelp.generate(); //生成Token
                    chinaset.setToken(StringStatic.REDIS_TOKEN + generate); //存入对象

                    ObjectMapper mapper = new ObjectMapper();
                    String chinasetJson = mapper.writeValueAsString(chinaset); //转成json


/*                    jedisClient.set(StringStatic.REDIS_TOKEN + generate, chinasetJson);  //加入缓存
                    jedisClient.expire(StringStatic.REDIS_TOKEN + generate, 604800);//过期时间为一个星期*/

                    jedisClient.setkeyexp(StringStatic.REDIS_TOKEN + generate, chinasetJson, 604800);
                    iBaseDao.update(chinaset);
         /*           List<MenusRole> list = queryRole(chinaset.getSetRole());

                    for (MenusRole menusRole : list) {

                        strings.add(menusRole.getMenusByNumber().getmUrl());
                    }*/

                    return ZhongkaiResult.ok(chinaset);
                } catch (Exception e) {
                    e.printStackTrace();
                    return ZhongkaiResult.build(401, "转换失败,请联系管理员");
                }

            } else {
                return ZhongkaiResult.build(401, "密码错误,登录失败");
            }
        }
    }

    @Override
    public ZhongkaiResult user_out(String token) {

        if (StringUtils.isNullOrEmpty(token)) {
            return ZhongkaiResult.build(500, "token为空");
        }

        Long delete = null;
        try {
            delete = jedisClient.delete(token);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(500, "redis连接获取失败");
        }
        //      System.out.println(delete);


        if (100l == delete) {
            return ZhongkaiResult.build(500, "key不存在");
        } else {
            return ZhongkaiResult.ok();
        }


    }


}
